/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pe.emp.solbrillante.sales.view;

import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import pe.emp.solbrillante.sale.Main;
import pe.emp.solbrillante.sales.bean.PaqueteCompra;
import pe.emp.solbrillante.sales.bean.Proveedor;

/**
 *
 * @author Ronald
 */
public class JCompra extends javax.swing.JDialog {

    /**
     * Creates new form JCompra
     */
    public JCompra(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();    
        
           
         //pintamos el fondo de la ventana
        //((JFondo)jventana).setImagen("fondo_subVentanal_II.jpg");
               
        //ArrayList<Producto> productos = Main.myService.queryAllProductos();
        ArrayList<Proveedor> proveedores = Main.myService.queryAllProveedores();
        
       
         //recorremos desde 1 porque no queremos el nombre de la etiqueta
        for(int i=1; i<proveedores.size();i++ ){       
//          this.jComboBox1.addItem(proveedores.get(i).getNombre());
//          combobox de objetos :  se sobreescribe el metodo toString() en proveedores
            this.jComboBox1.addItem(proveedores.get(i));        
        }
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableListaPaquetesProveedorCompra = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButtonGuardarCompra = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jTextFieldTotalPedido = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Registro de Compra");

        jLabel2.setText("Proveedor :");

        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jTableListaPaquetesProveedorCompra.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTableListaPaquetesProveedorCompra.addInputMethodListener(new java.awt.event.InputMethodListener() {
            public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
            }
            public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
                jTableListaPaquetesProveedorCompraInputMethodTextChanged(evt);
            }
        });
        jTableListaPaquetesProveedorCompra.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTableListaPaquetesProveedorCompraKeyReleased(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jTableListaPaquetesProveedorCompraKeyTyped(evt);
            }
        });
        jScrollPane1.setViewportView(jTableListaPaquetesProveedorCompra);

        jButton1.setText("Agregar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButtonGuardarCompra.setText("Guardar Modificacion");
        jButtonGuardarCompra.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonGuardarCompraActionPerformed(evt);
            }
        });

        jButton3.setText("Eliminar");

        jLabel3.setText("Total :");

        jTextFieldTotalPedido.setText("0");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(89, 89, 89)
                        .addComponent(jLabel1))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addGap(157, 157, 157)
                            .addComponent(jButton1)
                            .addGap(18, 18, 18)
                            .addComponent(jButtonGuardarCompra)
                            .addGap(18, 18, 18)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel3)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jTextFieldTotalPedido, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addComponent(jButton3)))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addGap(36, 36, 36)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 521, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel2)
                                    .addGap(74, 74, 74)
                                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                .addContainerGap(42, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextFieldTotalPedido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButtonGuardarCompra)
                    .addComponent(jButton3))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        // TODO add your handling code here:
        
        Proveedor proveedor = (Proveedor)this.jComboBox1.getSelectedItem();
        MostarProductosDeProveedor(proveedor);
        
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void jButtonGuardarCompraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGuardarCompraActionPerformed
        // TODO add your handling code here:
          // TODO add your handling code here:
        
                    //int col = this.jTableListaPaquetesProveedor.getModel().getColumnCount();
//                    int fil = this.jTableListaPaquetesProveedorCompra.getModel().getRowCount(); 
//                    System.out.println("nro rows : " + fil);
//                    
//                    for( int i=0; i<fil; i++)
//                    {
//                       int cod =   Integer.parseInt( jTableListaPaquetesProveedorCompra.getModel().getValueAt(i, 0).toString() );
//                       int can =   Integer.parseInt( jTableListaPaquetesProveedorCompra.getModel().getValueAt(i, 5).toString() );//getValueAt(i, 6) modificacion!!!!!
//                       
//                       System.out.print("codigo : "+cod+" cantidad : "+can);
//                       int res_insert = Main.myService.queryInsertaCompraPaquete(cod,can);
//                       System.out.println("insertada fila :" + i);                      
//                       
//                       System.out.print(res_insert);
//                    }
            // guardar registro docuem
        
    }//GEN-LAST:event_jButtonGuardarCompraActionPerformed

    private void jTableListaPaquetesProveedorCompraInputMethodTextChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_jTableListaPaquetesProveedorCompraInputMethodTextChanged
        // TODO add your handling code here:
       // System.out.print("fila : " + this.jTableListaPaquetesProveedorCompra.getEditingRow()+",col : " + this.jTableListaPaquetesProveedorCompra.getEditingColumn());
    }//GEN-LAST:event_jTableListaPaquetesProveedorCompraInputMethodTextChanged

    private void jTableListaPaquetesProveedorCompraKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTableListaPaquetesProveedorCompraKeyTyped
     
    }//GEN-LAST:event_jTableListaPaquetesProveedorCompraKeyTyped

    private void jTableListaPaquetesProveedorCompraKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTableListaPaquetesProveedorCompraKeyReleased
        // TODO add your handling code here:
      //  System.out.print("fila : " + this.jTableListaPaquetesProveedorCompra.getEditingRow()+",col : " + this.jTableListaPaquetesProveedorCompra.getEditingColumn());
        
       System.out.println("TECLA: " + evt.getKeyChar());
        
        int iRowEdit = jTableListaPaquetesProveedorCompra.getEditingRow();        
        int iColEdit = jTableListaPaquetesProveedorCompra.getEditingColumn();
        
        int colum = jTableListaPaquetesProveedorCompra.getSelectedColumn();
        int row = jTableListaPaquetesProveedorCompra.getSelectedRow();
        System.out.println("rc=" + iRowEdit +"cr=" +iColEdit + "st:"+ ",COL:" +colum+ ",ROW:" +row);
        int pedido = Integer.parseInt(jTableListaPaquetesProveedorCompra.getValueAt(row, colum).toString());
        Float precio = Float.parseFloat(jTableListaPaquetesProveedorCompra.getValueAt(row, colum-2).toString());
        Float subtotal =pedido*precio;
        jTableListaPaquetesProveedorCompra.getModel().setValueAt(subtotal, row, colum+1);
        
        this.jTextFieldTotalPedido.setText(sumaPedido().toString());
        
    }//GEN-LAST:event_jTableListaPaquetesProveedorCompraKeyReleased

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JCompra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JCompra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JCompra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JCompra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                JCompra dialog = new JCompra(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButtonGuardarCompra;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableListaPaquetesProveedorCompra;
    private javax.swing.JTextField jTextFieldTotalPedido;
    // End of variables declaration//GEN-END:variables

    private void MostarProductosDeProveedor(Proveedor proveedorDeproductoCompra) {
        //Declaramos las clases necesarias para la conexion     
            
            DefaultTableModel modelo;                               
            
            modelo = new DefaultTableModel(){
            boolean[] canEdit = new boolean [] { false, false,false, false, false, false , true , false};

            @Override
                         public boolean isCellEditable(int rowIndex, int columnIndex) {
                             return canEdit [columnIndex];
                         }

            };
            
            this.jTableListaPaquetesProveedorCompra.setModel(modelo); 
            
        
            
            System.out.println(proveedorDeproductoCompra.getId());   
            //ArrayList<Paquete> paquetesxproveedor = Main.myService.queryPaquetesxProveedor(proveedorDeproducto.getId());
            ArrayList<PaqueteCompra> paquetesxproveedor = Main.myService.queryPaquetesxProveedorS(proveedorDeproductoCompra.getId());
                 
    
            modelo.addColumn("Codigo");
            modelo.addColumn("Proveedor");
            modelo.addColumn("Producto");
            modelo.addColumn("Unidades");
            modelo.addColumn("PrecioxPaquete");
            modelo.addColumn("Cantidad_actual");
            
            modelo.addColumn("Pedido");
            modelo.addColumn("Subtotal");
            
            
//            this.jTableListaPaquetesProveedorCompra.getModel().addTableModelListener(new TableModelListener() {
//            @Override
//            public void tableChanged(TableModelEvent e) {
//                //JOptionPane.showMessageDialog(null, "Han cambiado los datos.");
//                int iRowEdit = jTableListaPaquetesProveedorCompra.getEditingRow();
//                int iColEdit = jTableListaPaquetesProveedorCompra.getEditingColumn();
//                System.out.println("rc=" + iRowEdit +"cr=" +iColEdit + "st:");
//                //Float subTotalRegistro = (Float) jTableListaPaquetesProveedorCompra.getValueAt(iRowEdit , 6) * (Float) jTableListaPaquetesProveedorCompra.getValueAt(iRowEdit , 4);
//                //jTableListaPaquetesProveedorCompra.getModel().setValueAt(34, 0, 7);
//                //RegCantidad(34,0,7);
//                //jTableListaPaquetesProveedorCompra.setv
//                //JOptionPane.showMessageDialog(null,"rc=" + iRowEdit +"cr=" +iColEdit);              
//                //System.out.println("rc=" + iRowEdit +"cr=" +iColEdit + "st:" + jTableListaPaquetesProveedorCompra.getValueAt(iRowEdit , 6));              
//                jTableListaPaquetesProveedorCompra.getModel().setValueAt(24 , 0,0);
//                
//                }
//
//         
//            });
            
           System.out.println("size : " + paquetesxproveedor.size());
            for (int i = 0; i < paquetesxproveedor.size(); i++) {                           
                //Extraemos los datos del ResultSet nombre=nombre de la columna              
                Object[] fila = new Object[8];                
                
                fila[0]=paquetesxproveedor.get(i).getCodigo();
                fila[1]=paquetesxproveedor.get(i).getNom_prov();
                fila[2]=paquetesxproveedor.get(i).getNom_prd();
                fila[3]=paquetesxproveedor.get(i).getUnixpaquete();
                fila[4]=paquetesxproveedor.get(i).getPrecioxpaquete();
                fila[5]=paquetesxproveedor.get(i).getCantidad();
                fila[6]=0;
                fila[7]=0;
                
                //System.out.println(paquetesxproveedor.get(i).getId()+"..."+paquetesxproveedor.get(i).getCantidad_actual());
                modelo.addRow(fila);                  
            }                           
            //jTableListaPaquetesProveedorCompra.getModel().setValueAt(23 , 0,7);      
    }

    private Double sumaPedido() {
            Double  total_pedido;       
            total_pedido = 0.0;
            for (int i = 0; i < this.jTableListaPaquetesProveedorCompra.getRowCount(); i++) {                                           
                total_pedido = total_pedido + Float.parseFloat(jTableListaPaquetesProveedorCompra.getValueAt(i, 7).toString());              
            }   
            
            System.out.println("total:"+total_pedido);
            return total_pedido;
    }


 
}
